import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';
import { 
  getSellerProducts, 
  createProduct, 
  updateProduct, 
  deleteProduct,
  uploadProductImage,
  getSellerOrders,
  shipOrder,
  batchShipOrders,
  cancelOrder,
  refundOrder,
  getComplaints,
  getComplaintDetail,
  replyComplaint,
  resolveComplaint,
  closeComplaint,
  updateProductStatus
} from '../../api/seller';

// 模拟延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 使用模拟数据
const useMock = false;

export const useSellerStore = defineStore('seller', {
  state: () => ({
    products: [],
    orders: [],
    salesRecords: [],
    currentProduct: null,
    currentOrder: null,
    salesData: null,
    complaints: [],
    currentComplaint: null,
    loading: false
  }),

  getters: {
    pendingOrders: (state) => state.orders.filter(order => order.status === 'pending'),
    processingOrders: (state) => state.orders.filter(order => order.status === 'processing'),
    completedOrders: (state) => state.orders.filter(order => order.status === 'completed'),
    cancelledOrders: (state) => state.orders.filter(order => order.status === 'cancelled'),
    totalSalesValue: (state) => state.salesRecords.reduce((sum, record) => sum + record.totalAmount, 0),
    totalProductsCount: (state) => state.products.length
  },

  actions: {
    // 商品管理相关方法
    async fetchProducts() {
      this.loading = true;
      try {
        console.log('开始获取卖家商品列表...');
        const result = await getSellerProducts();
        console.log('卖家商品列表API响应:', result);
        
        if (result.success && result.code === 200) {
          const products = result.data || [];
          console.log('处理前的商品数据:', products);
          
          // 处理数据，确保数据类型正确
          const processedProducts = products.map(product => {
            return {
              ...product,
              // 确保数字类型
              price: typeof product.price === 'string' ? parseFloat(product.price) : product.price,
              stock: typeof product.stock === 'string' ? parseInt(product.stock) : product.stock,
              status: typeof product.status === 'string' ? parseInt(product.status) : product.status,
              // 确保数组类型
              suitableCrops: Array.isArray(product.suitableCrops) ? product.suitableCrops : 
                            (typeof product.suitableCrops === 'string' ? 
                              (product.suitableCrops ? JSON.parse(product.suitableCrops) : []) : []),
              certificates: Array.isArray(product.certificates) ? product.certificates : 
                           (typeof product.certificates === 'string' ? 
                             (product.certificates ? JSON.parse(product.certificates) : []) : [])
            };
          });
          
          console.log('处理后的商品数据:', processedProducts);
          return processedProducts;
        } else {
          throw new Error(result.message || '获取商品列表失败');
        }
      } catch (error) {
        console.error('获取商品列表失败', error);
        ElMessage.error('获取商品列表失败：' + (error.message || '未知错误'));
        return [];
      } finally {
        this.loading = false;
      }
    },

    async createProduct(productData) {
      this.loading = true;
      try {
        console.log('开始创建商品...', productData);
        const result = await createProduct(productData);
        console.log('创建商品响应:', result);
        
        if (result.success && result.code === 200) {
          // 将新创建的商品添加到商品列表
          if (result.data) {
            this.products.unshift(result.data);
          }
          return result.data;
        } else {
          throw new Error(result.message || '创建商品失败');
        }
      } catch (error) {
        console.error('创建商品失败', error);
        ElMessage.error('创建商品失败：' + (error.message || '未知错误'));
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async updateProduct(productData) {
      this.loading = true;
      try {
        console.log('开始更新商品...', productData);
        
        // 确保productData中有image字段
        if (!productData.image && productData.id) {
          // 如果没有提供新图片，查找当前商品并使用其现有图片
          const existingProduct = this.products.find(item => item.id === productData.id);
          if (existingProduct && existingProduct.image) {
            productData.image = existingProduct.image;
            console.log('使用现有商品图片:', productData.image);
          }
        }
        
        const result = await updateProduct(productData);
        console.log('更新商品响应:', result);
        
        if (result.success && result.code === 200) {
          // 更新商品列表中的对应商品
          const index = this.products.findIndex(item => item.id === productData.id);
          if (index !== -1) {
            this.products[index] = { ...this.products[index], ...result.data };
          }
          return result.data;
        } else {
          throw new Error(result.message || '更新商品失败');
        }
      } catch (error) {
        console.error('更新商品失败', error);
        ElMessage.error('更新商品失败：' + (error.message || '未知错误'));
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async deleteProduct(productId) {
      this.loading = true;
      try {
        console.log('开始删除商品...', productId);
        const result = await deleteProduct(productId);
        console.log('删除商品响应:', result);
        
        if (result.success && result.code === 200) {
          // 从商品列表中移除已删除的商品
          const index = this.products.findIndex(item => item.id === productId);
          if (index !== -1) {
            this.products.splice(index, 1);
          }
          return true;
        } else {
          throw new Error(result.message || '删除商品失败');
        }
      } catch (error) {
        console.error('删除商品失败', error);
        ElMessage.error('删除商品失败：' + (error.message || '未知错误'));
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async updateProductStatus(productId, status) {
      this.loading = true;
      try {
        console.log('开始更新商品状态...', productId, status);
        
        // 确保status是数字类型
        const statusNum = typeof status === 'string' ? parseInt(status) : status;
        
        // 调用专门的状态更新API
        const response = await updateProductStatus(productId, statusNum);
        console.log('更新商品状态响应:', response);
        
        if (response.success && response.code === 200) {
          // 更新商品列表中的状态
          const index = this.products.findIndex(item => item.id === productId);
          if (index !== -1) {
            this.products[index].status = statusNum;
          }
          
          // 刷新商品列表
          await this.fetchProducts();
          return true;
        } else {
          throw new Error(response.message || '更新商品状态失败');
        }
      } catch (error) {
        console.error('更新商品状态失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async deleteProducts(productIds) {
      this.loading = true;
      try {
        if (useMock) {
          // 模拟批量删除商品
          await delay(500);
          return { success: true, count: productIds.length };
        } else {
          // 实际API调用
          const response = await fetch('/api/seller/products/batch-delete', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ ids: productIds })
          });
          return await response.json();
        }
      } catch (error) {
        console.error('批量删除商品失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async updateProductsStatus(productIds, status) {
      this.loading = true;
      try {
        console.log('开始批量更新商品状态...', productIds, status);
        
        // 确保status是数字类型
        const statusNum = typeof status === 'string' ? parseInt(status) : status;
        
        // 获取所有需要更新的商品
        const productsToUpdate = this.products.filter(product => 
          productIds.includes(product.id)
        );
        
        if (productsToUpdate.length === 0) {
          throw new Error('未找到需要更新的商品');
        }
        
        // 逐个更新商品状态
        const updatePromises = productsToUpdate.map(product => {
          const updatedProduct = { ...product, status: statusNum };
          return updateProduct(updatedProduct);
        });
        
        const results = await Promise.all(updatePromises);
        console.log('批量更新商品状态响应:', results);
        
        // 更新本地商品列表
        productIds.forEach(id => {
          const index = this.products.findIndex(item => item.id === id);
          if (index !== -1) {
            this.products[index] = { ...this.products[index], status: statusNum };
          }
        });
        
        return results;
      } catch (error) {
        console.error('批量更新商品状态失败', error);
        ElMessage.error('批量更新商品状态失败：' + (error.message || '未知错误'));
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 订单管理相关方法
    async fetchOrders() {
      this.loading = true;
      try {
        if (useMock) {
          // 模拟数据
          await delay(500);
          return mockOrders;
        } else {
          // 实际API调用
          const response = await getSellerOrders();
          console.log('获取到的订单数据:', response);
          
          // 处理订单数据，确保状态和商品信息正确
          if (response && response.data) {
            return response.data.map(order => {
              // 确保订单数据格式一致
              return {
                id: order.id,
                orderNumber: order.orderNo || '',
                buyerId: order.buyerId,
                buyerName: order.buyerName || '',
                buyerPhone: order.contactPhone || '',
                sellerId: order.sellerId,
                sellerName: order.sellerName || '',
                productId: order.productId,
                productName: order.productName || '',
                productImage: order.productImage || '',
                price: order.price || 0,
                quantity: order.quantity || 0,
                unit: order.unit || '个',
                totalAmount: order.totalAmount || 0,
                status: order.status, // 保留数字状态码
                address: order.address || '',
                orderDate: order.orderTime || new Date().toISOString(),
                payDate: order.payTime,
                shipDate: order.shipTime,
                completeDate: order.completeTime,
                note: order.remark || '',
                createTime: order.createTime,
                updateTime: order.updateTime,
                // 添加物流信息（如果有）
                logistics: order.shipTime ? {
                  company: '物流公司', // 这里可能需要从后端获取
                  trackingNumber: '物流单号', // 这里可能需要从后端获取
                  shipDate: order.shipTime
                } : null
              };
            });
          }
          return [];
        }
      } catch (error) {
        console.error('获取订单列表失败', error);
        return [];
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 获取订单统计数据
     */
    async getOrderStats() {
      try {
        // 这里应该调用后端接口获取统计数据
        // 目前使用模拟数据
        const pendingCount = this.getOrdersByStatus('paid').length;
        
        return {
          pending: pendingCount,
          today: Math.round(Math.random() * 10),
          todayIncome: Math.round(Math.random() * 1000),
          monthIncome: Math.round(Math.random() * 10000)
        };
      } catch (error) {
        console.error('获取订单统计失败', error);
        return {
          pending: 0,
          today: 0,
          todayIncome: 0,
          monthIncome: 0
        };
      }
    },
    
    /**
     * 按状态获取订单
     */
    getOrdersByStatus(status) {
      return this.orders.filter(order => order.status === status);
    },
    
    /**
     * 订单状态映射
     */
    mapOrderStatus(status) {
      // 根据后端返回的数字状态映射为前端状态字符串
      const statusMap = {
        0: 'pending',  // 待付款
        1: 'paid',     // 已付款，待发货
        2: 'shipped',  // 已发货
        3: 'completed', // 已完成
        4: 'cancelled', // 已取消
        5: 'refunding', // 退款中
        6: 'refunded'   // 已退款
      };
      
      return statusMap[status] || 'pending';
    },
    
    /**
     * 生成订单状态历史
     */
    generateStatusHistory(order) {
      const history = [];
      
      // 创建订单
      history.push({
        status: 'pending',
        time: order.createTime,
        remark: '订单创建成功'
      });
      
      // 支付成功
      if (order.payTime) {
        history.push({
          status: 'paid',
          time: order.payTime,
          remark: '订单支付成功'
        });
      }
      
      // 已发货
      if (order.shipTime) {
        history.push({
          status: 'shipped',
          time: order.shipTime,
          remark: '商家已发货'
        });
      }
      
      // 已完成
      if (order.completeTime) {
        history.push({
          status: 'completed',
          time: order.completeTime,
          remark: '订单已完成'
        });
      }
      
      // 已取消（这里没有取消时间字段，需要根据实际情况添加）
      if (order.status === 4) {
        history.push({
          status: 'cancelled',
          time: order.updateTime,
          remark: '订单已取消'
        });
      }
      
      // 退款相关（这里没有退款时间字段，需要根据实际情况添加）
      if (order.status === 5 || order.status === 6) {
        history.push({
          status: order.status === 5 ? 'refunding' : 'refunded',
          time: order.updateTime,
          remark: order.status === 5 ? '退款申请中' : '退款已完成'
        });
      }
      
      return history;
    },

    async shipOrder(shipData) {
      this.loading = true;
      try {
        if (useMock) {
          // 模拟发货
          await delay(500);
          return { 
            success: true,
            orderId: shipData.orderId,
            logistics: {
              company: shipData.company,
              trackingNumber: shipData.trackingNumber,
              shipDate: new Date().toISOString()
            }
          };
        } else {
          // 实际API调用
          const response = await shipOrder(shipData);
          console.log('发货响应:', response);
          return {
            success: true,
            ...response
          };
        }
      } catch (error) {
        console.error('订单发货失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async batchShipOrders(orderIds) {
      this.loading = true;
      try {
        if (useMock) {
          // 模拟批量发货
          await delay(500);
          return { success: true, count: orderIds.length };
        } else {
          // 实际API调用
          const response = await fetch('/api/seller/orders/batch-ship', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ ids: orderIds })
          });
          return await response.json();
        }
      } catch (error) {
        console.error('批量发货失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async cancelOrder(orderId) {
      this.loading = true;
      try {
        if (useMock) {
          // 模拟取消订单
          await delay(500);
          return { success: true, orderId };
        } else {
          // 实际API调用
          const response = await fetch(`/api/seller/orders/${orderId}/cancel`, {
            method: 'POST'
          });
          return await response.json();
        }
      } catch (error) {
        console.error('取消订单失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async refundOrder(orderId) {
      this.loading = true;
      try {
        if (useMock) {
          // 模拟退款
          await delay(500);
          return { success: true, orderId };
        } else {
          // 实际API调用
          const response = await fetch(`/api/seller/orders/${orderId}/refund`, {
            method: 'POST'
          });
          return await response.json();
        }
      } catch (error) {
        console.error('退款失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 销售数据相关方法
    async getSalesData(params) {
      this.loading = true;
      try {
        if (useMock) {
          // 模拟销售数据
          await delay(700);
          return generateMockSalesData(params);
        } else {
          // 实际API调用
          const queryParams = new URLSearchParams(params).toString();
          const response = await fetch(`/api/seller/sales?${queryParams}`);
          return await response.json();
        }
      } catch (error) {
        console.error('获取销售数据失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 设置当前商品
    setCurrentProduct(product) {
      this.currentProduct = product;
    },
    
    // 设置当前订单
    setCurrentOrder(order) {
      this.currentOrder = order;
    },

    // 获取投诉列表
    async fetchComplaints() {
      try {
        this.loading = true;
        const response = await getComplaints();
        if (response.success) {
          this.complaints = response.data;
          return this.complaints;
        }
        ElMessage.error(response.message || '获取投诉列表失败');
        return [];
      } catch (error) {
        console.error('获取投诉列表失败', error);
        ElMessage.error('获取投诉列表失败');
        return [];
      } finally {
        this.loading = false;
      }
    },

    // 获取投诉详情
    async getComplaintDetail(id) {
      try {
        this.loading = true;
        const response = await getComplaintDetail(id);
        if (response.success) {
          this.currentComplaint = response.data;
          return this.currentComplaint;
        }
        ElMessage.error(response.message || '获取投诉详情失败');
        return null;
      } catch (error) {
        console.error('获取投诉详情失败', error);
        ElMessage.error('获取投诉详情失败: ' + (error.message || '未知错误'));
        return null;
      } finally {
        this.loading = false;
      }
    },

    // 回复投诉
    async replyComplaint(id, content) {
      try {
        this.loading = true;
        const response = await replyComplaint(id, content);
        if (response.success) {
          ElMessage.success('回复已提交');
          // 刷新投诉列表
          await this.fetchComplaints();
          return true;
        }
        ElMessage.error(response.message || '提交回复失败');
        return false;
      } catch (error) {
        console.error('提交回复失败', error);
        ElMessage.error('提交回复失败: ' + (error.message || '未知错误'));
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 解决投诉
    async resolveComplaint(id, solution) {
      try {
        this.loading = true;
        const response = await resolveComplaint(id, solution);
        if (response.success) {
          ElMessage.success('投诉已解决');
          // 刷新投诉列表
          await this.fetchComplaints();
          return true;
        }
        ElMessage.error(response.message || '解决投诉失败');
        return false;
      } catch (error) {
        console.error('解决投诉失败', error);
        ElMessage.error('解决投诉失败: ' + (error.message || '未知错误'));
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 关闭投诉
    async closeComplaint(id) {
      try {
        this.loading = true;
        const response = await closeComplaint(id);
        if (response.success) {
          ElMessage.success('投诉已关闭');
          // 刷新投诉列表
          await this.fetchComplaints();
          return true;
        }
        ElMessage.error(response.message || '关闭投诉失败');
        return false;
      } catch (error) {
        console.error('关闭投诉失败', error);
        ElMessage.error('关闭投诉失败: ' + (error.message || '未知错误'));
        return false;
      } finally {
        this.loading = false;
      }
    },

    async uploadProductImage(file) {
      this.loading = true;
      try {
        console.log('开始上传商品图片...', file);
        const result = await uploadProductImage(file);
        console.log('上传商品图片响应:', result);
        
        if (result.success && result.code === 200) {
          return result.data;
        } else {
          throw new Error(result.message || '上传商品图片失败');
        }
      } catch (error) {
        console.error('上传商品图片失败', error);
        ElMessage.error('上传商品图片失败：' + (error.message || '未知错误'));
        throw error;
      } finally {
        this.loading = false;
      }
    }
  }
});

// 模拟数据生成函数
function generateMockProducts() {
  const categories = [
    'grain', 'vegetable', 'fruit', 'meat', 'aquatic', 
    'egg', 'dairy', 'tea', 'oil', 'other'
  ];
  
  const productNames = {
    grain: ['有机大米', '小麦粉', '黑米', '糯米', '燕麦'],
    vegetable: ['新鲜蔬菜', '西红柿', '黄瓜', '胡萝卜', '土豆'],
    fruit: ['红富士苹果', '香蕉', '橙子', '葡萄', '西瓜'],
    meat: ['黑猪肉', '牛肉', '羊肉', '鸡肉', '鸭肉'],
    aquatic: ['大闸蟹', '基围虾', '三文鱼', '草鱼', '鲈鱼'],
    egg: ['土鸡蛋', '鸭蛋', '鹅蛋', '鹌鹑蛋', '皮蛋'],
    dairy: ['纯牛奶', '酸奶', '奶酪', '黄油', '炼乳'],
    tea: ['龙井茶', '普洱茶', '铁观音', '大红袍', '白茶'],
    oil: ['橄榄油', '菜籽油', '花生油', '葵花籽油', '芝麻油'],
    other: ['蜂蜜', '坚果', '干果', '调味料', '罐头']
  };
  
  const statuses = ['active', 'inactive', 'pending', 'rejected'];
  const units = ['kg', '斤', '箱', '袋', '瓶', '个'];
  
  return Array.from({ length: 30 }).map((_, index) => {
    const category = categories[Math.floor(Math.random() * categories.length)];
    const nameList = productNames[category] || productNames.other;
    const name = nameList[Math.floor(Math.random() * nameList.length)];
    const price = parseFloat((Math.random() * 100 + 5).toFixed(2));
    const stock = Math.floor(Math.random() * 1000);
    const sales = Math.floor(Math.random() * stock);
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const unit = units[Math.floor(Math.random() * units.length)];
    
    return {
      id: `P${10000 + index}`,
      productCode: `SKU${100000 + index}`,
      name: `${name} ${index + 1}号`,
      category,
      price,
      unit,
      stock,
      image: `https://picsum.photos/seed/${index}/200/200`,
      description: `这是一款优质的${name}，采用天然种植方式，无农药残留，健康美味。`,
      origin: ['山东', '四川', '云南', '广东', '黑龙江'][Math.floor(Math.random() * 5)],
      productionDate: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      shelfLife: [30, 60, 90, 180, 365][Math.floor(Math.random() * 5)],
      certificates: ['organic', 'green', 'pollution_free'].slice(0, Math.floor(Math.random() * 3) + 1),
      status,
      sales,
      createdAt: new Date(Date.now() - Math.random() * 60 * 24 * 60 * 60 * 1000).toISOString(),
      updatedAt: new Date(Date.now() - Math.random() * 10 * 24 * 60 * 60 * 1000).toISOString()
    };
  });
}

function generateMockOrders() {
  const statuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled', 'refunding', 'refunded'];
  const paymentMethods = ['online', 'cod', 'transfer', 'alipay', 'wechat'];
  const deliveryMethods = ['express', 'self'];
  const products = generateMockProducts().slice(0, 15);
  
  return Array.from({ length: 40 }).map((_, index) => {
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const product = products[Math.floor(Math.random() * products.length)];
    const quantity = Math.floor(Math.random() * 10) + 1;
    const totalAmount = parseFloat((product.price * quantity + (Math.random() * 10 + 5)).toFixed(2));
    const orderDate = new Date(Date.now() - Math.random() * 60 * 24 * 60 * 60 * 1000);
    
    const statusHistory = [];
    statusHistory.push({
      status: 'pending',
      time: new Date(orderDate.getTime()).toISOString(),
      remark: '买家下单'
    });
    
    if (status !== 'pending') {
      statusHistory.push({
        status: 'paid',
        time: new Date(orderDate.getTime() + 2 * 60 * 60 * 1000).toISOString(),
        remark: '买家付款'
      });
    }
    
    if (['shipped', 'completed'].includes(status)) {
      statusHistory.push({
        status: 'shipped',
        time: new Date(orderDate.getTime() + 24 * 60 * 60 * 1000).toISOString(),
        remark: '卖家发货'
      });
    }
    
    if (status === 'completed') {
      statusHistory.push({
        status: 'completed',
        time: new Date(orderDate.getTime() + 3 * 24 * 60 * 60 * 1000).toISOString(),
        remark: '买家确认收货'
      });
    }
    
    if (status === 'cancelled') {
      statusHistory.push({
        status: 'cancelled',
        time: new Date(orderDate.getTime() + 1 * 60 * 60 * 1000).toISOString(),
        remark: '买家取消订单'
      });
    }
    
    if (['refunding', 'refunded'].includes(status)) {
      statusHistory.push({
        status: 'refunding',
        time: new Date(orderDate.getTime() + 4 * 24 * 60 * 60 * 1000).toISOString(),
        remark: '买家申请退款'
      });
      
      if (status === 'refunded') {
        statusHistory.push({
          status: 'refunded',
          time: new Date(orderDate.getTime() + 5 * 24 * 60 * 60 * 1000).toISOString(),
          remark: '卖家同意退款'
        });
      }
    }
    
    // 添加物流信息
    const logistics = status === 'shipped' || status === 'completed' ? {
      company: ['SF', 'YTO', 'ZTO', 'STO', 'EMS'][Math.floor(Math.random() * 5)],
      trackingNumber: `${['SF', 'YT', 'ZT', 'ST', 'EM'][Math.floor(Math.random() * 5)]}${Math.random().toString().slice(2, 13)}`,
      shipDate: new Date(orderDate.getTime() + 24 * 60 * 60 * 1000).toISOString()
    } : null;
    
    return {
      id: `O${100000 + index}`,
      orderNumber: `ORD${Date.now().toString().slice(0, 10)}${index.toString().padStart(4, '0')}`,
      buyerName: `用户${Math.floor(Math.random() * 1000) + 1}`,
      buyerPhone: `1${Math.floor(Math.random() * 9) + 1}${Math.random().toString().slice(2, 12)}`,
      productId: product.id,
      productName: product.name,
      price: product.price,
      quantity,
      unit: product.unit,
      totalAmount,
      address: `${['北京市', '上海市', '广州市', '深圳市', '杭州市'][Math.floor(Math.random() * 5)]}${['朝阳区', '浦东新区', '天河区', '南山区', '西湖区'][Math.floor(Math.random() * 5)]}${['望京', '张江', '珠江新城', '科技园', '文三路'][Math.floor(Math.random() * 5)]}${Math.floor(Math.random() * 100) + 1}号`,
      paymentMethod: paymentMethods[Math.floor(Math.random() * paymentMethods.length)],
      deliveryMethod: deliveryMethods[Math.floor(Math.random() * deliveryMethods.length)],
      deliveryFee: parseFloat((Math.random() * 10 + 5).toFixed(2)),
      status,
      note: Math.random() > 0.7 ? `请尽快发货，谢谢！${Math.floor(Math.random() * 1000)}` : null,
      orderDate: orderDate.toISOString(),
      statusHistory,
      logistics
    };
  });
}

function generateMockSalesData(params) {
  const timeRange = params.timeRange || 'month';
  
  // 统计数据
  const totalSales = parseFloat((Math.random() * 50000 + 10000).toFixed(2));
  const salesGrowth = parseFloat((Math.random() * 30 - 15).toFixed(2));
  const totalOrders = Math.floor(Math.random() * 200 + 50);
  const ordersGrowth = parseFloat((Math.random() * 30 - 10).toFixed(2));
  const soldProductCount = Math.floor(Math.random() * 50 + 10);
  const productCountGrowth = parseFloat((Math.random() * 20 - 5).toFixed(2));
  const customerCount = Math.floor(Math.random() * 100 + 30);
  const customerGrowth = parseFloat((Math.random() * 25 - 8).toFixed(2));
  
  // 趋势数据
  let trendData = [];
  let categories = ['grain', 'vegetable', 'fruit', 'meat', 'aquatic', 'egg', 'dairy', 'tea', 'oil', 'other'];
  let regions = ['北京', '上海', '广东', '浙江', '江苏', '四川', '湖北', '湖南', '山东', '河北', '河南', '辽宁', '吉林', '黑龙江', '安徽', '福建', '江西', '山西', '陕西', '贵州', '云南', '广西', '内蒙古', '新疆', '西藏', '宁夏', '甘肃', '青海', '天津', '重庆', '海南'];
  
  // 生成趋势数据
  switch (timeRange) {
    case 'today':
      // 24小时数据
      trendData = Array.from({ length: 24 }).map((_, index) => {
        const hour = index.toString().padStart(2, '0');
        return {
          date: `${hour}:00`,
          sales: parseFloat((Math.random() * 1000 + 100).toFixed(2)),
          orders: Math.floor(Math.random() * 10 + 1)
        };
      });
      break;
    case 'week':
      // 7天数据
      const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      trendData = days.map((day, index) => {
        return {
          date: day,
          sales: parseFloat((Math.random() * 5000 + 500).toFixed(2)),
          orders: Math.floor(Math.random() * 30 + 5)
        };
      });
      break;
    case 'month':
      // 30天数据
      trendData = Array.from({ length: 30 }).map((_, index) => {
        const day = (index + 1).toString().padStart(2, '0');
        return {
          date: `${day}日`,
          sales: parseFloat((Math.random() * 2000 + 300).toFixed(2)),
          orders: Math.floor(Math.random() * 20 + 3)
        };
      });
      break;
    case 'year':
      // 12个月数据
      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
      trendData = months.map((month) => {
        return {
          date: month,
          sales: parseFloat((Math.random() * 30000 + 5000).toFixed(2)),
          orders: Math.floor(Math.random() * 200 + 50)
        };
      });
      break;
    default:
      // 默认30天数据
      trendData = Array.from({ length: 30 }).map((_, index) => {
        const day = (index + 1).toString().padStart(2, '0');
        return {
          date: `${day}日`,
          sales: parseFloat((Math.random() * 2000 + 300).toFixed(2)),
          orders: Math.floor(Math.random() * 20 + 3)
        };
      });
  }
  
  // 分类数据
  const categoryData = categories.map(category => {
    return {
      category,
      amount: parseFloat((Math.random() * 5000 + 500).toFixed(2)),
      count: Math.floor(Math.random() * 30 + 5)
    };
  });
  
  // 地区数据
  const regionData = regions.map(region => {
    return {
      region,
      amount: parseFloat((Math.random() * 3000 + 200).toFixed(2)),
      count: Math.floor(Math.random() * 20 + 2)
    };
  });
  
  // 热销商品
  const products = generateMockProducts().slice(0, 10);
  const hotProducts = products.map(product => {
    return {
      id: product.id,
      name: product.name,
      category: product.category,
      image: product.image,
      sales: Math.floor(Math.random() * 500 + 50),
      amount: parseFloat((Math.random() * 10000 + 1000).toFixed(2))
    };
  }).sort((a, b) => b.sales - a.sales);
  
  // 最新订单
  const recentOrders = generateMockOrders().slice(0, 5);
  
  return {
    totalSales,
    salesGrowth,
    totalOrders,
    ordersGrowth,
    soldProductCount,
    productCountGrowth,
    customerCount,
    customerGrowth,
    trendData,
    categoryData,
    hotProducts,
    recentOrders,
    regionData
  };
} 